/****************************************************************************
 Copyright (c) 2010-2012 cocos2d-x.org
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011      Zynga Inc.

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

var BattleLayer = cc.Layer.extend({
    ctor:function(background,playerData,enemyData,init_cards){
        this._super();
        this.background = background;
        this.enemyData = enemyData;
        this.playerData = playerData;
        this.cards = init_cards;

        this._cardSpirtes = [];
        this._cardChoosed = [];
        this.player = null;
        this.enemy = null;
    },
    onEnter:function(){
        this._super();

        var ui = UISystem.selectUI("BattleUI");

        //background
        var size = cc.Director.getInstance().getWinSize();
        var lazyLayer = cc.Layer.create();
        this.addChild(lazyLayer);
        if(this.background)
        {
            this.sprite = cc.Sprite.create(this.background);
            this.sprite.setPosition(cc.p(size.width /2,size.height/2));
            lazyLayer.addChild(this.sprite);
        }
        //player
        this.player = new PlayerActionSet(lazyLayer,cc.p(size.width*0.35,size.height*0.45),cc.p(size.width*0.55,size.height*0.60),1,false);
        this.player.stand();

        this.enemy = new PlayerActionSet(lazyLayer,cc.p(size.width*0.60,size.height*0.65),cc.p(size.width*0.40,size.height*0.50),1,true);
        this.enemy.stand();
        //set ui
        ui.setSelfWuli(this.playerData.wuli);
        ui.setSelfHp(this.playerData.hp);
        ui.setSelfName(this.playerData.name);

        ui.setEnemyWuli(this.enemyData.wuli);
        ui.setEnemyHp(this.enemyData.hp);
        ui.setEnemyName(this.enemyData.name);

        //cards
        for(var i in this.cards){
            if(this.cards.hasOwnProperty(i)){
                var cardName = this.cards[i].name;
                if(this.cards[i].params) {
                    var cardNum = this.cards[i].params.num;
                    var cardSprite = this.createCardSprite(cardName,cardNum,i);
                    this._cardSpirtes.push(cardSprite);
                    this.addChild(cardSprite);
                }else{
                    var cardSprite = this.createCardSprite(cardName,null,i);
                    this._cardSpirtes.push(cardSprite);
                    this.addChild(cardSprite);
                }
            }
        }
        //register UI event
        var self = this;
        BattleUI.onChangeDefense(function(){self.updateCards()});
        BattleUI.onAccept(function(){
            var cards = [];
            for(var i = 0;i < self._cardSpirtes.length;++i){
                var card = self._cardSpirtes[i];
                if(card.isChoosed()){
                    cards.push(i);
                }
            }
            app.getSession().notify(new RequestPlayNofity(app.getSession().getPlayer().id,cards,BattleUI.isDefense()));
            BattleUI.disableAccept();
        });

        this.setTouchEnabled(true);
        this.setMouseEnabled(true);
    },

    createCardSprite:function(card,num,index){
        cardSprite = new CardSprite();
        cardSprite.initWithCardName(card,num);
        cardSprite.setAnchorPoint(cc.p(0,0));
        cardSprite.setPosition(10 + index*95,35);
        //this.addChild(cardSprite);
        //this._cardSpirtes.push(cardSprite);
        return cardSprite;
    },

    onTouchesBegan:function(touch, event){
        for(var i = this._cardSpirtes.length - 1;i >= 0; --i){
            var card = this._cardSpirtes[i];
            if(cc.Rect.CCRectContainsPoint(card.touchRect(),touch[0].getLocation())){
                if(!this.cardCanChoose(card) && !card.isChoosed()){
                    return;
                }
                card.toggleCard();
                if(card.isChoosed()){
                    //add card choosed
                    this._cardChoosed.push(card);
                    this.updateCards();
                }else{
                    //remove card cancel choose
                    for(var j = 0;j < this._cardChoosed.length; ++j){
                        if(this._cardChoosed[j] === card){
                            this._cardChoosed.splice(j,1);
                            this.updateCards();
                            break;
                        }
                    }
                }
                this.updateUI();
                break;
            }
        }
    },

    updateCards:function(){
        for(var i = this._cardSpirtes.length - 1;i >= 0; --i){
            var card = this._cardSpirtes[i];
            if(this.cardCanChoose(card)){
                card.enable();
            }else{
                if(!card.isChoosed()){
                    card.disable();
                }
            }
        }
    },

    cardCanDraw:function(){
        return this._cardChoosed.length > 0;
    },
    cardCanChoose:function(card){
        var num = this._cardChoosed.length;
        if(!BattleUI.isDefense()){
            /*特殊卡牌只能出一张*/
            if(card.type != "attack"){
                if(this._cardChoosed.length >0 ){
                    return false;
                }
            }
            if(this._cardChoosed.length > 0 && this._cardChoosed[0].type !="attack"){
                return false;
            }
        }
        /*普通卡牌最多三张*/
        if(this._cardChoosed.length >=3){
            return false;
        }
        return true;
    },

    updateUI:function(){
        if(this.cardCanDraw()){
            UISystem.activeLayerApply("enableAccept");
        }else{
            UISystem.activeLayerApply("disableAccept");
        }
    },

    playCards:function(selfRequests,selfCards,enemyRequests,enemyCards,actions,draws){
        var self = this;
        var cards_fade_time = 1.0;
        var show_played_time = 0.2;
        var played_cards_fade_time = 1.0;
        var playedCards = [];
        var selfPlayerId = app.getSession().getPlayer().id;
        function dismiss_cards(){
            var playCards = [];
            for(var i in self._cardSpirtes){
                var cardSprite = self._cardSpirtes[i];
                var fadeOutAction = cc.FadeOutWithChildren.create(cards_fade_time);
                cardSprite.runAction(fadeOutAction);
            }
        }
        function show_played_cards(){
            for(var index in selfCards){
                var card = selfCards[index];
                var cardSprite = self.createSelfPlayCardSprite(card.name,card.params.num,index,125 *(selfRequests.length - 1));

                var action = cc.FadeInWithChildren.create(show_played_time);
                cardSprite.runAction(action);
                playedCards.push(cardSprite);
            }

            for(var index in enemyCards){
                var card = enemyCards[index];
                var cardSprite = self.createEnemyPlayCardSprite(card.name,card.params.num,index,125 *(enemyRequests.length - 1));

                var action = cc.FadeInWithChildren.create(show_played_time);
                cardSprite.runAction(action);
                playedCards.push(cardSprite);
            }
        }
        function dismiss_played_cards(){
            for(var i in playedCards){
                var cardSprite = playedCards[i];
                var action = cc.FadeOutWithChildren.create(played_cards_fade_time);
                cardSprite.runAction(action);
                cardSprite.scheduleOnce(function(){self.removeChild(this)},played_cards_fade_time);
            }
        }
        function play_action(selfAction,selfData,enemyAction,enemyData){
            switch(selfAction.type){
                case ACTION_TYPE.ATTACK:

                    break;
                case ACTION_TYPE.DAMAGE:
                    break;
                case ACTION_TYPE.DRAW:
                    break;
                default:
                    break;
            }
        }
        function play_actions(){
            for(var action in actions){
                //    actions.push([round,selfId,selfAction,targetId,targetAction,selfDate,targetDate]);
                var round = action[0];
                var cId = action[1];
                var cAction = action[2];
                var hId = action[3];
                var hAction = action[4];
                var cData = action[5];
                var hData = action[6];
                var selfAction = null,enemyAction = null,selfData = null,enemyData = null;
                if(selfPlayerId === cId){
                    selfAction = cAction;
                    selfData = cData;
                    enemyAction = hAction;
                    enemyAction = hData;
                }else{
                    selfAction = hAction;
                    selfData = hData;
                    enemyAction = cAction;
                    enemyAction = cData;
                }

            }
        }
        var delay = cards_fade_time;
        this.scheduleOnce(dismiss_cards,delay);
        delay += show_played_time;
        this.scheduleOnce(show_played_cards,delay);
        delay += 2.0;
        delay += played_cards_fade_time;
        this.scheduleOnce(dismiss_played_cards,delay);
    },

    createSelfPlayCardSprite:function(card,num,index,start_x){
        cardSprite = new CardSprite();
        cardSprite.initWithCardName(card,num);
        cardSprite.setAnchorPoint(cc.p(0,0));
        cardSprite.setPosition(start_x + index*125,35);
        this.addChild(cardSprite);
        //this._cardSpirtes.push(cardSprite);
        return cardSprite;
    },
    createEnemyPlayCardSprite:function(card,num,index,start_x){
        cardSprite = new CardSprite();
        cardSprite.initWithCardName(card,num);
        cardSprite.setAnchorPoint(cc.p(0,0));
        cardSprite.setPosition(start_x + index*125,270);
        this.addChild(cardSprite);
        //this._cardSpirtes.push(cardSprite);
        return cardSprite;
    },
});

var BattleScene = cc.Scene.extend({
        ctor:function(background,playerData,enemyData,init_cards){
            this._super();
            this.background = background;
            this.playerData = playerData;
            this.enemyData = enemyData;
            this.init_cards = init_cards;
        },
        onEnter : function(){
            this._super();
            var layer = new BattleLayer(this.background,this.playerData,this.enemyData,this.init_cards);
            this.addChild(layer);
            this.layer = layer;
        }
    }
)
